//
//  KDAddsubscribController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/5.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDAddsubscribController.h"
#import "KDSubscribTypeModel.h"
#import "KDSubscripRequestTool.h"
#import "KDAllSubscribeResult.h"

@interface KDAddsubscribController ()<UITableViewDelegate, UITableViewDataSource>
/**  <#Description#> */
@property (nonatomic, weak) UITableView *tableView;
/**  所有的板块汇总 */
@property (nonatomic, strong) NSArray *themeArr;

/**  所有未添加的板块汇总 */
@property (nonatomic, strong) NSMutableArray *unAddArr;

@end

@implementation KDAddsubscribController
#pragma mark - 懒加载区
- (NSMutableArray *)addArr
{
    if (!_addArr) {
        _addArr = [NSMutableArray array] ;
    }
    return _addArr;
}
- (NSMutableArray *)unAddArr
{
    if (!_unAddArr) {
        _unAddArr = [NSMutableArray array] ;
    }
    return _unAddArr;
}
- (NSArray *)themeArr
{
    if (!_themeArr) {
        _themeArr = [NSArray array] ;
    }
    return _themeArr;
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavBar];
    [self loadData];
    [self setupTableView];
    // Do any additional setup after loading the view from its nib.
}
//- (void)setThemeArr:(NSArray *)themeArr{
//    _themeArr = themeArr;
////    for (KDSubscribTypeModel *model in themeArr) {
////        if (model.isChecked isEqualToString:@"1"]) {
////            [self.addArr addObject:model];
////        }else{
////            [self.unAddArr addObject:model];
////        }
////    }
//}
#pragma mark - 板块布置区
- (void)setupTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, screenH - 44) style:UITableViewStyleGrouped];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.editing = YES;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    [self.view addSubview:tableView];
}
- (void)setupNavBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
}
#pragma mark - 事件点击区
/**
 *  返回按钮被点击了
 */
- (void)backViewClick{
//    [self.addArr addObjectsFromArray:self.unAddArr];
   // self.themeArr = [NSArray arrayWithArray:self.addArr];
//    for (int i = 0; i < self.themeArr.count; i++) {
//        KDSubscribTypeModel *model = self.themeArr[i];
//        model.orderNum = i;
//    }
    if (_delegate && [_delegate respondsToSelector:@selector(backViewClickWithThemeArr:)]) {
        [_delegate backViewClickWithThemeArr:self.addArr];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 网络请求区
/**
 *  拉取所有的可订阅类型
 */
- (void)loadData{
    KDBaseParam *param = [[KDBaseParam alloc]init];
    param.method = @"earlyWaringSetting/pushInfoTypes";
    [KDSubscripRequestTool getAllSubscribeModelWithParam:param success:^(KDAllSubscribeResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.themeArr = responseObejct.data;
            [self splitData];
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**  分割开已订阅和未订阅的模型 */
- (void)splitData{
    for (KDSubscribTypeModel *model in self.themeArr) {
        
        for (KDSubscribTypeModel *addModel in self.addArr) {
            if (model.ID == addModel.ID) {
                model.isChecked = YES;
                break;
            }
        }
        //如果加过一轮还没有变的话，说明是未订阅的
        if (!model.isChecked) {
            [self.unAddArr addObject:model];
        }
    }
    
}
#pragma mark - 通知接收区


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.addArr.count && self.unAddArr.count) {
        return 2;
    }else {
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (!self.addArr.count) {//当全部删除的时候，这个arr就没数据了，section0装的就是self.unAddArr的数据
            return  self.unAddArr.count;
        }
         return self.addArr.count;
    }else{
        return  self.unAddArr.count;
    }
   
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0 && self.addArr.count) {
        
        return @"已添加";
        
    }else{
        return @"未添加";
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId =@"addSubCell";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
//        cell =[[[NSBundle mainBundle]loadNibNamed:@"<#nibName#>" owner:self options:nil]lastObject];
         cell.imageView.image = [UIImage imageNamed:@"未添加"];
        
    }
    KDSubscribTypeModel *model;
    if (indexPath.section == 0 && self.addArr.count) {
        model = self.addArr[indexPath.row];
        cell.textLabel.text = model.name;
       
    }else{
        model = self.unAddArr[indexPath.row];
        cell.textLabel.text = model.name;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && self.addArr.count) {
        return UITableViewCellEditingStyleDelete;
    }else{
        return UITableViewCellEditingStyleInsert;
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger section ;
    NSInteger r ;
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        NSInteger row = [indexPath row];
        KDSubscribTypeModel *model = self.addArr[indexPath.row];
        //        通过获取的索引值删除数组中的值
        [self.addArr removeObjectAtIndex:row];
        model.isChecked = NO;
        if (!self.addArr.count ||!self.unAddArr.count) {
            [self.unAddArr addObject:model];
            section = 1;
            r = self.unAddArr.count -1;
            [self.tableView reloadData];
            return;
        }
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

        [self.unAddArr addObject:model];
        section = 1;
        r = self.unAddArr.count -1;
    //        删除单元格的某一行时，在用动画效果实现删除过程
        [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:r inSection:section]] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }else if (editingStyle==UITableViewCellEditingStyleInsert){
        NSInteger row = [indexPath row];
        KDSubscribTypeModel *model = self.unAddArr[indexPath.row];

        [self.unAddArr removeObjectAtIndex:row];
        model.isChecked = YES;
//        model.orderNum = self.addArr.count;
        if (!self.addArr.count ||!self.unAddArr.count) {
            
            [self.addArr addObject:model];
            [self.tableView reloadData];
            return;
        }
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

        [self.addArr addObject:model];
        //        通过获取的索引值删除数组中的值
        section = 0;
        r = self.addArr.count -1;
        [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:r inSection:section]] withRowAnimation:UITableViewRowAnimationAutomatic];

    }
//    [self.tableView reloadRowsAtIndexPaths:<#(nonnull NSArray<NSIndexPath *> *)#> withRowAnimation:<#(UITableViewRowAnimation)#>];
}
@end
